//
//  ESCategoryBar.m
//  Eyeshot
//
//  Created by admin on 15/7/1.
//  Copyright (c) 2015年 eyeshot. All rights reserved.
//

#define kButtonTagBaseValue (100)
#import "ESCategoryBar.h"

@interface ESCategoryBar ()
@property (nonatomic, weak) UIButton *selectedBtn;
@end

@implementation ESCategoryBar

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        //高度是固定的
        self.backgroundColor = [UIColor whiteColor];
        self.height = CATEGORY_BAR_HEIGHT;
        [self createButtonWithTitle:@"全部"];
        [self createButtonWithTitle:@"视频"];
        [self createButtonWithTitle:@"图片"];
        [self createButtonWithTitle:@"段子"];
        [self createButtonWithTitle:@"排行"];
    }
    return self;
    
}


- (void)setDelegate:(id<ESCategoryBarDelegate>)delegate {
    _delegate = delegate;
    UIButton *btn = (UIButton *)[self viewWithTag:kButtonTagBaseValue + 0];
    btn.selected = YES;
    _selectedBtn = btn;
    
}

- (UIButton *) createButtonWithTitle:(NSString *)title {
    
    UIButton *btn = [[UIButton alloc] init];
    //[self viewWithTag:0] 取得的是self自身,所以这里加个基数
    btn.tag = self.subviews.count + kButtonTagBaseValue;
    [btn addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:btn];
    // 设置高亮的时候不要让图标变色
    btn.adjustsImageWhenHighlighted = NO;
  
    [btn setTitle:title forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    btn.titleLabel.textAlignment = NSTextAlignmentCenter;
        
    return btn;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    // 设置按钮的frame
    
    NSUInteger btnCount = self.subviews.count;
    UIImage *image = [UIImage imageWithColor:ESAlphaColor(228, 228, 228, 0.3) height:2 width:SCREEN_WIDTH/btnCount];
    CGFloat btnW = self.width / btnCount;
    CGFloat btnH = self.height;
    for (int i = 0; i<btnCount; i++) {
        UIButton *btn = self.subviews[i];
        btn.height = btnH;
        btn.width = btnW;
        btn.x = i * btnW;
        [btn setBackgroundImage:image forState:UIControlStateSelected];

    }
}

- (void)setCurrentPage:(NSInteger)currentPage {
    UIButton *btn = (UIButton *)self.subviews[currentPage];
    [self changeSelectedButton:btn];
    _selectedBtn = btn;
}


- (void)clickButton:(UIButton *)btn {
    [self changeSelectedButton:btn];
    
    if ([_delegate respondsToSelector:@selector(categoryBar:didSelectFromIndex:toIndex:)]) {
        [_delegate categoryBar:self didSelectFromIndex:(_selectedBtn.tag - kButtonTagBaseValue) toIndex:(btn.tag - kButtonTagBaseValue)];
    }
    _selectedBtn = btn;
}

- (void)changeSelectedButton:(UIButton *)btn {
    _selectedBtn.selected = NO;
    btn.selected = YES;
}

@end
